<template>
  <div id="userAccoutTemplate">
    <el-form :model="searchForm" label-width="120px" ref="searchForm" class="search-ruleForm">
      <div class="form-line">
        <el-form-item label="账号:" class="user-account" prop="username">
          <el-input v-model="searchForm.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称:" class="nickname" prop="nickname">
            <el-input v-model="searchForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" class="email" prop="email">
            <el-input v-model="searchForm.email"></el-input>
        </el-form-item>
        </div>
        <div class="date-time-line form-line">
          <el-form-item label="时间范围" class="timeRange" prop="timeRange">
              <el-date-picker v-model="searchForm.dateTimes" type="datetimerange"
                range-separator="至" start-placeholder="开始时间" end-placeholde="结束时间" align="right" 
               format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickOptions">
              </el-date-picker>
          </el-form-item>
        </div>
        <div class="button-line">
            <el-button type="primary" @click="submitForm('searchForm')">查询</el-button>
            <el-button @click="resetForm('searchForm')">重置</el-button>
        </div>
    </el-form>
    <el-table border :data="userAccounts" style="width: 100%">
        <el-table-column prop="username" label="用户账号" width="200"></el-table-column>
        <el-table-column prop="nickname" label="用户名称" width="200"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="250"></el-table-column>
        <el-table-column prop="regTime" label="注册时间" width="250"></el-table-column>
        <el-table-column width="350"
        label="操作">
        <template slot-scope="scope">
          <el-button @click="openQueryDialog(scope.row)" type="text" size="small">查看已有角色</el-button>
          <el-button type="text" @click="openEditDialog(scope.row)" size="small">增加授权角色</el-button>  
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="hadleSizeChange" @current-change="handleCurrentChange"
      :current-page="currentPage" :page-sizes="pageSizes" :page-size="pageSize"
       layout="total, sizes, prev, pager, next, jumper" :total="totalCounts">    
    </el-pagination>
    <el-dialog class="query-dialog" :title="queryDialogTitle" :visible.sync="queryDialogVisible" 
      width="35%">
      <el-table ref="qeuryDialogTable" :data="userRoles" highlight-current-row 
        @current-change="handleCurrentRowChange" style="width: 100%" @select="checkRoles"
      >  
         <el-table-column type="selection" width="55">
         </el-table-column>
         <el-table-column property="id" label="角色ID" width="80">
         </el-table-column>
         <el-table-column property="roleCode" label="角色编码" width="120">
         </el-table-column>
         <el-table-column property="roleName" label="角色名称" width="120">
         </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeQueryDialog">取 消</el-button>
        <el-button type="primary" @click="delUserRole">解除授权</el-button>
      </span>
    </el-dialog >
    <el-dialog class="edit-dialog" :title="editDialogTitle" :visible.sync="eidtDialogVisible" width="35%">
      <el-table ref="editDialogTable" :data="noAllocateRoles" highlight-current-row 
        style="width: 100%" tooltip-effect="dark"
        @selection-change="handleSelectionChange" @select="selectChecked">
         <el-table-column type="selection" width="55">
         </el-table-column>
         <el-table-column property="id" label="角色ID" width="80">
         </el-table-column>
         <el-table-column property="roleCode" label="角色编码" width="120">
         </el-table-column>
         <el-table-column property="roleName" label="角色名称" width="120">
         </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeEidtDialog">取消</el-button>
        <el-button type="primary" @click="addUserRole">添加授权</el-button>
      </span> 
    </el-dialog>
  </div>
</template>

<script>
import {queryUserInfosByPage} from '@/api/user'
import {getRolesByUid, getUserNotAllocateRoles, addRolesForUser, delRolesForUser} from '@/api/role'

export default {
  data() {
    let startDate = new Date()
    startDate.setTime(startDate.getTime() -  3600 * 1000 * 24 * 7)
    const endDate =new Date()
    const startYear = startDate.getFullYear()
    const startMonth = startDate.getMonth()>8?''+(startDate.getMonth()+1):'0'+(startDate.getMonth()+1)
    const startMonthDay = startDate.getDate()>9?''+startDate.getDate():'0'+startDate.getDate()
    const startHours = startDate.getHours()>9?''+startDate.getHours():'0'+startDate.getHours()
    const startMinutes = startDate.getMinutes()>9?''+startDate.getMinutes():'0'+startDate.getMinutes()
    const startSeconds = startDate.getSeconds()>9?''+startDate.getSeconds():'0'+startDate.getSeconds()
    const startDateTimeStr = startYear+'-'+startMonth+'-'+startMonthDay+' '+startHours+':'+startMinutes+':'+startSeconds
    const endYear = endDate.getFullYear()
    const endMonth = endDate.getMonth()>8?''+(endDate.getMonth()+1):'0'+(endDate.getMonth()+1)
    const endMonthDay = endDate.getDate()>9?''+endDate.getDate():'0'+endDate.getDate()
    const endHours = endDate.getHours()>9?''+endDate.getHours():'0'+endDate.getHours()
    const endMinutes = endDate.getMinutes()>9?''+endDate.getMinutes():'0'+endDate.getMinutes()
    const endSeconds = endDate.getSeconds()>9?''+endDate.getSeconds():'0'+endDate.getSeconds()
    const endDateTimeStr = endYear+'-'+endMonth+'-'+endMonthDay+' '+endHours+':'+endMinutes+':'+endSeconds
    return {
      searchForm: {
        username: '',
        nickname: '',
        email: '',
        dateTimes: [startDateTimeStr,endDateTimeStr]
      },
      userAccounts: [{ id: 1, username: 'zhangsan', nickname: '张三', email: 'zhangsan2021@163.com', regTime: '2021-06-20 23:58:48' },
        { id: 2, username: 'heshengfu', nickname: '程序员阿福', email: 'heshengfu2018@163.com', regTime: '2021-06-21 00:00:13' },
        { id: 3, username: 'lisi', nickname: '李四', email: 'lisi1998@163.com', regTime: '2021-08-04 00:45:38' }],
      pickOptions: {
        shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
      },
      currentPage: 1,
      pageSizes: [10,20,50,100,500],
      pageSize: 10,
      totalCounts: 120,
      queryDialogVisible: false,
      eidtDialogVisible: false,
      currentRoleRow: 0,
      selectedUid: null,
      queryDialogTitle: '',
      editDialogTitle: '',
      userRoles: [
        {id:1,roleCode:'admin',roleName:'管理员'},
        {id:2,roleCode:'user',roleName:'普通用户'}
        ],
      checkedRoles: [],
      multipleSelection: [],
      noAllocateRoles: [],
    }
  },
  methods: {
    submitForm(formName) {
      console.log(formName)
      const formData = this.searchForm
      const queyParam = {
        username: formData.username,
        nickname: formData.nickname,
        email: formData.email,
        regStartTime: formData.dateTimes && formData.dateTimes.length>0?formData.dateTimes[0]:'',
        regEndTime: formData.dateTimes && formData.dateTimes.length>0?formData.dateTimes[1]:''
      }
      console.log(queyParam)
      const pageParam = {
        currPage: this.currentPage,
        pageSize: this.pageSize
      }
      console.log(pageParam)
      queryUserInfosByPage(queyParam, pageParam).then(res=>{
          if(res.status===200 && res.data.status===200){
            const pageData = res.data.data
            this.totalCounts = pageData.totalRows
            this.userAccounts = pageData.result
          }else{
            this.$message({
              showClose: true,
              message: res.data.msg,
              type: 'error'
            })
          }
      }).catch(err=>{
        this.$message({
          showClose: true,
          message: err,
          type: 'error'
        })
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    hadleSizeChange(val) {
      console.log(val);
      this.pageSize = val
      this.submitForm('searchForm')
    },
    handleCurrentChange(val){
       console.log(val);
       this.currentPage = val
       this.submitForm('searchForm')
    },
    getDateString(date) {
      const year = date.getFullYear()
      const month = date.getMonth()>8?''+(date.getMonth()+1):'0'+(date.getMonth()+1)
      const monthDay = date.getDate()>9?''+date.getDate():'0'+date.getDate()
      const hours = date.getHours()>9?''+date.getHours():'0'+date.getHours()
      const minutes = date.getMinutes()>9?''+date.getMinutes():'0'+date.getMinutes()
      const seconds = date.getSeconds()>9?''+date.getSeconds():'0'+date.getSeconds()
      const dateStr = year+'-'+month+'-'+monthDay+' '+hours+':'+minutes+':'+seconds
      return dateStr
    },
    openQueryDialog(row) {
      console.log(row)
      this.queryDialogVisible = true
      const uid = row.id
      this.selectedUid = uid
      this.queryDialogTitle = '用户 '+row.nickname+' 已有角色'
      getRolesByUid(uid).then(res=>{
        if(res.status===200 && res.data.status===200){
          this.userRoles = res.data.data
        }
      }).catch(err=>{
         this.$message({
           showClose: true,
           message: err,
           type: 'error'
         })
      })
    },
    openEditDialog(row){
      console.log(row)
      this.eidtDialogVisible = true
      const uid = row.id
      this.selectedUid = uid
      this.editDialogTitle = '给用户 '+row.nickname+' 添加角色'
      getUserNotAllocateRoles(uid).then(res=>{
        if(res.status===200 && res.data.status===200){
           this.noAllocateRoles = res.data.data
        }
      }).catch(err=>{
         console.error(err)
      })
    },
    handleSelectionChange(rows){
      
    },
    checkRoles(selection,row){
      debugger
      this.checkedRoles = selection
    },
    selectChecked(selection,row){
      this.multipleSelection = selection
    },
    closeQueryDialog(){
      this.queryDialogVisible = false
    },
    handleCurrentRowChange(row){
      this.currentRoleRow = row
      this.$refs['qeuryDialogTable'].setCurrentRow(row)
    },
    closeEidtDialog(){
      this.eidtDialogVisible = false
    },
    addUserRole(){
        if (this.multipleSelection.length > 0) {
            let roleIds = []
            const uid = this.selectedUid
            for (let i = 0; i < this.multipleSelection.length; i++) {
                 let row = this.multipleSelection[i];
                 roleIds.push(row.id)
            }
            addRolesForUser(roleIds, uid).then(res=>{
               if (res.status===200 && res.data.status===200) {
                   this.$message({
                     showClose: true,
                     message: '授权角色成功',
                     type: 'success'
                   })
               }
            }).catch(err=>{
              this.$message({
                     showClose: true,
                     message: '授权角色成功失败',
                     type: 'error'
                   })
            })
        }else{
            this.$message({
              showClose: true,
              message: '请先选择授权的角色',
              type: 'warning'
            })
        }
        this.eidtDialogVisible = false
    },
    delUserRole() {
      if(this.checkedRoles.length > 0){
          let roleIds = []
          const uid = this.selectedUid
          for (let i = 0; i < this.checkedRoles.length; i++) {
                let row = this.checkedRoles[i];
                roleIds.push(row.id)
          }
          delRolesForUser(roleIds, uid).then(res=>{
              if(res.status===200 && res.data.status===200){
                  this.$message({
                     showClose: true,
                     message: '解除授权角色成功',
                     type: 'success'
                   })
               }
            }).catch(err=>{
               this.$message({
                     showClose: true,
                     message: '解除授权角色失败',
                     type: 'error'
                   })
            })
      }else{
        this.$message({
            showClose: true,
            message: '请先选择要解除授权的角色',
            type: 'warning'
        })
      }
      this.queryDialogVisible = false
    }
  }
}
</script>
<style lang="scss" scoped>
  .search-ruleForm{
    width: 100%;
    height: 180px;
    .el-form-item__label {
      text-align: right;
    }
    .form-line {
      height: 32px;
      width: 100%;
      margin-bottom: 20px;
      .el-form-item {
        width: 32%;
        float: left;
      }
    }
    .button-line {
      height: 40px;
      width: 100%;
      margin-top: 25px;
    }
  }
</style>
